import axios from 'axios'
import store from '@/store/index.js'
import config from './baseUrl'
import {
	Dialog,Notify 
} from 'vant';
const http = {}
let  baseURL = config.baseUrl
var instance = axios.create({
	timeout: 30000,
	baseURL,
	withCredentials: true,
	validateStatus(status) {
		return status >= 200 && status < 300
	}
})

// 添加请求拦截器
instance.interceptors.request.use(
	function(config) {
		// 请求头添加token
		if (store.state.userToken) {
			config.headers.Authorization = `${store.state.userToken}`
		}
		return config
	},
	function(error) {
		return Promise.reject(error)
	}
)

// 响应拦截器即异常处理
instance.interceptors.response.use(
	response => {
		return response.data
	},
	err => {
		if (err && err.response) {
			// console.log("成功")
		} else {
			err.message = '连接服务器失败'
		}
		Dialog({
			message: err.message
		})
		return Promise.reject(err.response)
	}
)

http.get = function(url, options) {
	let loading
	// if (!options || options.isShowLoading !== false) {
	// 	loading = document.getElementById('ajaxLoading')
	// 	loading.style.display = 'block'
	// }
	let params = {
		params: options
	}
	return new Promise((resolve, reject) => {
		instance
			.get(url, params)
			.then(response => {
				// if (!options || options.isShowLoading !== false) {
				// 	loading = document.getElementById('ajaxLoading')
				// 	loading.style.display = 'none'
				// }
				if (response.respCode.code =='EDI-10000') {
					resolve(response.data)
				} else {
					Dialog({
						message: response.respCode.message
					})
					reject(response.respCode.message)
				}
			})
			.catch(e => {
				Notify({message:e})
			})
	})
}

http.post = function(url, data, options) {
	let loading
	// if (!options || options.isShowLoading !== false) {
	// 	loading = document.getElementById('ajaxLoading')
	// 	loading.style.display = 'block'
	// }
	return new Promise((resolve, reject) => {
		instance
			.post(url, data, options)
			.then(response => {
				if (response.respCode.code == 'EDI-10000') {
					resolve(response.data)
				} else {
					Dialog({
						message: response.respCode.message
					})
					reject(response.message)
				}
			})
			.catch(e => {
				Notify({message:e})
				reject()
			})
	})
}


http.put = function(url, data, options) {
	let loading
	// if (!options || options.isShowLoading !== false) {
	// 	loading = document.getElementById('ajaxLoading')
	// 	loading.style.display = 'block'
	// }
	return new Promise((resolve, reject) => {
		instance
			.put(url, data, options)
			.then(response => {
				// if (!options || options.isShowLoading !== false) {
				// 	loading = document.getElementById('ajaxLoading')
				// 	loading.style.display = 'none'
				// }
				if (response.respCode.code = 'EDI-10000') {
					resolve(response.data)
				} else {
					Dialog({
						message: response.respCode.message
					})
					reject(response.message)
				}
			})
			.catch(e => {
				Notify({message:e})
			})
	})
}

export default http
